package com.zhy.springcloud.controller;

import com.zhy.springcloud.enetities.CommonResult;
import com.zhy.springcloud.entities.Payment;
import com.zhy.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.annotation.Resource;
import javax.swing.text.DefaultEditorKit;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhy
 * @Description 支付模块控制层
 * @ClassName PaymentController
 * @Date 2020/11/12 18:51
 **/
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/payment/add")
    public CommonResult create(@RequestBody Payment payment){
        paymentService.create(payment);
        return new  CommonResult<>(200,"SUCCESS");
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable Long id){
        log.debug("SUCCESS");
        Payment paymentById = paymentService.getPaymentById(id);
        return new CommonResult(200,"SUCCESS,serverPort="+serverPort,paymentById);
    }

    @GetMapping("/payment/dicovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("*****element"+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"+ instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return services;
    }
    @GetMapping("/payment/lb")
    public String getPaymentLb(){
        return serverPort;
    }

    @GetMapping("/paymet/feign/timeout")
    public String paymentFeignTimeOut(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;

    }

    @GetMapping("/payment/zipkin")
    public  String paymentZipkin(){
        return "hi,i am paymentZipkin server fall back";
    }


}
